tr命令

tr命令用于转换或删除文件中的字符,可以读文件也可以从标准输入设备读取数据,经过字符串转译后,将结果输出到标准输出设备。

语法

tr [OPTION]... SET1 [SET2]

参数

解释序列

示例

file.txt文件内容如下。

Hello World

将文件中的字母全部转换为大写。

cat file.txt | tr [a-z] [A-Z]
# HELLO WORLD

同样可以使用[:lower][:upper]参数来实现。

cat file.txt | tr [:lower:] [:upper:]
# HELLO WORLD

将水平空白符转换为\t

cat file.txt | tr [:space:] "\t"
# Hello   World   

删除所有o字符。

cat file.txt | tr -d "o"
# Hell Wrld

删除所有数字。

echo "My ID is 73535" | tr -d [:digit:]
# My ID is

取出字符串中的数字。

echo "My ID is 73535" | tr -cd [:digit:]
# 73535

参考

https://www.runoob.com/linux/linux-comm-tr.html
https://www.tutorialspoint.com/unix_commands/tr.htm
https://www.geeksforgeeks.org/tr-command-in-unix-linux-with-examples/